package com.ali.niogroupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class GroupChatClient {
    private final SocketChannel socketChannel;
    private final Selector selector;

    public GroupChatClient(String ip, int port) {
        try {
            //构建客户端连接
            socketChannel = SocketChannel.open(new InetSocketAddress(ip, port));
            //设置客户端连接为非阻塞状态
            socketChannel.configureBlocking(false);
            //构建多路复用器
            selector = Selector.open();
            //在多路复用器中注册客户端数据传输事件
            socketChannel.register(selector, SelectionKey.OP_READ);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        GroupChatClient groupChatClient = new GroupChatClient("127.0.0.1", 8080);
        groupChatClient.start();
    }

    /**
     * 启动
     */
    public void start() {
        new Thread(() -> {
            try {
                while (true) {
                    //多路复用器阻塞，等待事件发生
                    selector.select();
                    handle();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }).start();

        //构建用户输入
        Scanner scanner = new Scanner(System.in);
        //检测是否输入
        while (scanner.hasNext()) {
            //获取用户输入
            String message = scanner.next();
            sendMessage(message);
        }
    }

    /**
     * 处理多路复用器事件
     */
    private void handle() {
        try {
            //构建缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int length;

            //获取多路复用器的所有事件
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                //判断是否是数据传输事件
                if (selectionKey.isReadable()) {
                    //获取客户端连接
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    StringBuilder stringBuffer = new StringBuilder();

                    try {
                        while (true) {
                            //写入内容至缓冲区
                            length = socketChannel.read(byteBuffer);
                            if (length > 0) {
                                //清理缓冲区
                                byteBuffer.clear();
                                stringBuffer.append(new String(byteBuffer.array(), 0, length));
                            } else if (length == 0) {
                                break;
                            }
                        }
                        System.out.println(stringBuffer);
                    } catch (IOException e) {
                        System.out.println(socketChannel.getRemoteAddress() + "：服务器离线");
                        //取消注册
                        selectionKey.cancel();
                        System.out.println("退出客户端");
                        //停止客户端
                        System.exit(0);
                    }
                }
                //移除事件
                iterator.remove();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 向服务器发送消息
     */
    private void sendMessage(String message) {
        try {
            //构建缓冲区
            ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8));
            //向客户端连接传输数据
            socketChannel.write(byteBuffer);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
